package starwars.example;

import static org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;

import com.badlogic.gdx.math.Vector2;
import com.google.gson.Gson;

import android.content.Context;
import android.util.Log;

public class FixtureAtlas{
	public class FixtureDataContainer{
		public class Asset{
			public String imagePath;  
			public int widthPx;
			public int heightPx;
			public Vector2 shape[];
			
			public void AlignByPixelToMeterRatioAndCenter(){
				for(int i=0;i<shape.length;i++){
					Vector2 v=shape[i];
					v.x=(v.x-widthPx/2)/PIXEL_TO_METER_RATIO_DEFAULT;
					v.y=(heightPx/2-v.y)/PIXEL_TO_METER_RATIO_DEFAULT;
					shape[i]=v;
				}
			}
			
			transient public TextureRegion mTextureRegion;
			public void loadImage(Engine engine,Context context){
				BitmapTextureAtlas mTexture = new BitmapTextureAtlas(widthPx, heightPx, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
				mTextureRegion=BitmapTextureAtlasTextureRegionFactory.createFromAsset(mTexture, context, imagePath, 0, 0);
				engine.getTextureManager().loadTexture(mTexture);
			}
			
			
		}
		
		public Map<String,Asset> assets;
		
		public void loadImages(Engine engine,Context context){
			Set<Entry<String, Asset>> set=assets.entrySet();
			Iterator<Entry<String, Asset>> i=set.iterator();
			while(i.hasNext()){
				Map.Entry<String,Asset> entry=  (Entry<String, Asset>) i.next();
				Asset asset=(Asset) entry.getValue();
				
				asset.AlignByPixelToMeterRatioAndCenter();
				asset.loadImage(engine, context);
			}
		}
	}

	FixtureDataContainer fdc;
	
	public void loadFromJSON(Engine engine,Context context,InputStream is) {
        Gson gson = new Gson();

		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		fdc=gson.fromJson(br,FixtureDataContainer.class);
		
		fdc.loadImages(engine,context);
		
        Log.d("JSON","loaded data:"+gson.toJson(fdc));
	}
}
